/**
 *
 */
package com.newworld.dmsapp2.util;

import java.io.IOException;
import java.net.SocketTimeoutException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.AbstractHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.util.EntityUtils;

import android.util.Log;

/**
 * 
 * 联网的Post和Get封装 已经是异步线程了 直接调用方法
 */
public class HttpUtil {
	static String result;

	static String sessionId;

	/**
	 * 
	 * @param url
	 *            发送请求的URL
	 * @return 服务器响应字符串
	 * @throws Exception
	 */
	public static String getRequest(final String url) throws Exception {
		final HttpClient httpClient = new DefaultHttpClient();
		System.out.println("<--getRequest()-->");
		FutureTask<String> task = new FutureTask<String>(
				new Callable<String>() {
					@Override
					public String call() throws Exception {
						System.out.println("<--call()-->");
						// 创建HttpGet对象。
						HttpGet get = new HttpGet(url);
						// 发送GET请求
						HttpResponse httpResponse = httpClient.execute(get);
						// 如果服务器成功地返回响应
						if (httpResponse.getStatusLine().getStatusCode() == 200) {
							System.out.println("<--result-->");
							// 获取服务器响应字符串
							String result = EntityUtils.toString(httpResponse
									.getEntity());
							System.out.println("###" + result);

							if (result.indexOf("[{") != -1) {
								result = result.replace("\n", "").replace("\r",
										"");
								// result=result.replace("\n", "");
								System.out.println("#" + result);
							}

							return result;

						} else {
							// Toast.makeText(HttpUtil.class, "未能正常获取数据 ！！",
							// Toast.LENGTH_LONG).show();
							System.out.println("<--can't return result-->");
						}
						return null;
					}
				});

		new Thread(task).start();
		return task.get();
	}

	/**
	 * @param url
	 *            发送请求的URL
	 * @param params
	 *            请求参数
	 * @return 服务器响应字符串
	 * @throws ExecutionException
	 * @throws InterruptedException
	 * @throws Exception
	 */
	public static String postRequest(final String url,
			final Map<String, String> rawParams) throws InterruptedException,
			ExecutionException {
		final HttpClient httpClient = new DefaultHttpClient();
		FutureTask<String> task = new FutureTask<String>(
				new Callable<String>() {
					@Override
					public String call() throws ParseException, IOException {
						// 创建HttpPost对象。
						HttpPost post = new HttpPost(url);
						// 如果传递参数个数比较多的话可以对传递的参数进行封装
						List<NameValuePair> params = new ArrayList<NameValuePair>();
						for (String key : rawParams.keySet()) {
							// 封装请求参数
							params.add(new BasicNameValuePair(key, rawParams
									.get(key)));
						}
						// 设置请求参数
						post.setEntity(new UrlEncodedFormEntity(params, "utf-8"));

						// 请求超时 add by risa
						httpClient.getParams().setParameter(
								CoreConnectionPNames.CONNECTION_TIMEOUT, 60000);// 60000
						// 读取超时 add by risa
						httpClient.getParams().setParameter(
								CoreConnectionPNames.SO_TIMEOUT, 60000);

						// 发送POST请求
						HttpResponse httpResponse = null;
						try {
							synchronized (httpClient) {
								httpResponse = httpClient.execute(post);
							}
						} catch (ConnectTimeoutException e) {
							Log.e("ConnectTimeoutException",
									"ConnectTimeoutException");
							e.printStackTrace();
						} catch (SocketTimeoutException e) {

							Log.e("SocketTimeoutException",
									"SocketTimeoutException");
							e.printStackTrace();

						}
						// 如果服务器成功地返回响应
						if (httpResponse.getStatusLine().getStatusCode() == 200) {
							// 获取服务器响应字符串
							String result = EntityUtils.toString(httpResponse
									.getEntity());

							return result;
						}
						return null;
					}
				});
		new Thread(task).start();
		return task.get();
	}
	/**
	 * @param url
	 *            发送请求的URL
	 * @param params
	 *            请求参数
	 * @return 服务器响应字符串
	 * @throws ExecutionException
	 * @throws InterruptedException
	 * @throws Exception
	 */
	public static String postRequestSe(final String url,
			final Map<String, String> rawParams,final String setsessionid) throws InterruptedException,
			ExecutionException {
		final HttpClient httpClient = new DefaultHttpClient();
		FutureTask<String> task = new FutureTask<String>(
				new Callable<String>() {
					@Override
					public String call() throws ParseException, IOException {
						// 创建HttpPost对象。
						HttpPost post = new HttpPost(url);
						if (null != setsessionid && !setsessionid.equals("")) {
							post.setHeader("Cookie", "JSESSIONID=" + setsessionid);
						}
						// 如果传递参数个数比较多的话可以对传递的参数进行封装
						List<NameValuePair> params = new ArrayList<NameValuePair>();
						for (String key : rawParams.keySet()) {
							// 封装请求参数
							params.add(new BasicNameValuePair(key, rawParams
									.get(key)));
						}
						// 设置请求参数
						post.setEntity(new UrlEncodedFormEntity(params, "utf-8"));

						// 请求超时 add by risa
						httpClient.getParams().setParameter(
								CoreConnectionPNames.CONNECTION_TIMEOUT, 60000);// 60000
						// 读取超时 add by risa
						httpClient.getParams().setParameter(
								CoreConnectionPNames.SO_TIMEOUT, 60000);

						// 发送POST请求
						HttpResponse httpResponse = null;
						try {
							synchronized (httpClient) {
								httpResponse = httpClient.execute(post);
							}
						} catch (ConnectTimeoutException e) {
							Log.e("ConnectTimeoutException",
									"ConnectTimeoutException");
							e.printStackTrace();
						} catch (SocketTimeoutException e) {

							Log.e("SocketTimeoutException",
									"SocketTimeoutException");
							e.printStackTrace();

						}
						// 如果服务器成功地返回响应
						if (httpResponse.getStatusLine().getStatusCode() == 200) {
							// 获取服务器响应字符串
							String result = EntityUtils.toString(httpResponse
									.getEntity());

							return result;
						}
						return null;
					}
				});
		new Thread(task).start();
		return task.get();
	}
	/**
	 * @param url
	 *            发送请求的URL
	 * @param params
	 *            请求参数
	 * @return 服务器响应字符串
	 * @throws ExecutionException
	 * @throws InterruptedException
	 * @throws Exception
	 */
	public static String loginpostRequest(final String url,
			final Map<String, String> rawParams) throws InterruptedException,
			ExecutionException {
		final HttpClient httpClient = new DefaultHttpClient();
		FutureTask<String> task = new FutureTask<String>(
				new Callable<String>() {
					@Override
					public String call() throws ParseException, IOException {
						// 创建HttpPost对象。
						HttpPost post = new HttpPost(url);
						// 如果传递参数个数比较多的话可以对传递的参数进行封装
						List<NameValuePair> params = new ArrayList<NameValuePair>();
						for (String key : rawParams.keySet()) {
							// 封装请求参数
							params.add(new BasicNameValuePair(key, rawParams
									.get(key)));
						}
						// 设置请求参数
						post.setEntity(new UrlEncodedFormEntity(params, "utf-8"));

						// 请求超时 add by risa
						httpClient.getParams().setParameter(
								CoreConnectionPNames.CONNECTION_TIMEOUT, 60000);// 60000
						// 读取超时 add by risa
						httpClient.getParams().setParameter(
								CoreConnectionPNames.SO_TIMEOUT, 60000);

						// 发送POST请求
						HttpResponse httpResponse = null;
						try {
							httpResponse = httpClient.execute(post);
						} catch (ConnectTimeoutException e) {
							Log.e("ConnectTimeoutException",
									"ConnectTimeoutException");
							e.printStackTrace();
						} catch (SocketTimeoutException e) {

							Log.e("SocketTimeoutException",
									"SocketTimeoutException");
							e.printStackTrace();

						}
						// 如果服务器成功地返回响应
						if (httpResponse.getStatusLine().getStatusCode() == 200) {
							// 获取服务器响应字符串
							String result = EntityUtils.toString(httpResponse
									.getEntity());
							List<Cookie> cookies = ((AbstractHttpClient) httpClient)
									.getCookieStore().getCookies();
							for (Cookie cookie : cookies) {
								// 这里是读取Cookie['PHPSESSID']的值存在静态变量中，保证每次都是同一个值
								sessionId = cookie.getValue();
								break;
							}

							return result;
						}
						return null;
					}
				});
		new Thread(task).start();
		return task.get();
	}

	/**
	 * @param url
	 *            发送请求的URL
	 * @param params
	 *            请求参数
	 * @return 服务器响应字符串
	 * @throws ExecutionException
	 * @throws InterruptedException
	 * @throws Exception
	 */
	public static String loginpostRequestSes(final String url,
			final Map<String, String> rawParams,final String setsessionid) throws InterruptedException,
			ExecutionException {
		final HttpClient httpClient = new DefaultHttpClient();
		FutureTask<String> task = new FutureTask<String>(
				new Callable<String>() {
					@Override
					public String call() throws ParseException, IOException {
						// 创建HttpPost对象。
						HttpPost post = new HttpPost(url);
						String result = "";
						//post.setHeader("Cookie", "JSESSIONID=" + "03236F972DB06FD00F37BD0CEF92B433");
						if (null != setsessionid && !setsessionid.equals("")) {
							post.setHeader("Cookie", "JSESSIONID=" + setsessionid);
						}
						// 如果传递参数个数比较多的话可以对传递的参数进行封装
						List<NameValuePair> params = new ArrayList<NameValuePair>();
						for (String key : rawParams.keySet()) {
							// 封装请求参数
							params.add(new BasicNameValuePair(key, rawParams
									.get(key)));
						}
						// 设置请求参数
						post.setEntity(new UrlEncodedFormEntity(params, "utf-8"));

						// 请求超时 add by risa
						httpClient.getParams().setParameter(
								CoreConnectionPNames.CONNECTION_TIMEOUT, 60000);// 60000
						// 读取超时 add by risa
						httpClient.getParams().setParameter(
								CoreConnectionPNames.SO_TIMEOUT, 60000);

						// 发送POST请求
						HttpResponse httpResponse = null;
						try {
							httpResponse = httpClient.execute(post);
						} catch (ConnectTimeoutException e) {
							Log.e("loginpostRequestSes",
									"ConnectTimeoutException");
							e.printStackTrace();
						} catch (SocketTimeoutException e) {

							Log.e("loginpostRequestSes",
									"SocketTimeoutException");
							e.printStackTrace();

						}
						// 如果服务器成功地返回响应
						if (httpResponse.getStatusLine().getStatusCode() == 200) {
							// 获取服务器响应字符串
							result = EntityUtils.toString(httpResponse
									.getEntity());
							List<Cookie> cookies = ((AbstractHttpClient) httpClient)
									.getCookieStore().getCookies();
							if(cookies.size() != 0){
								for (Cookie cookie : cookies) {
									// 这里是读取Cookie['PHPSESSID']的值存在静态变量中，保证每次都是同一个值
									sessionId = cookie.getValue();
									Log.e("loginpostRequestSes",
											"sessionId = "+sessionId);
									break;
									 
								}
							}else{
								if (null != setsessionid && !setsessionid.equals("")) {
									sessionId = setsessionid;
								}
							}
							

							//return result;
						}else{
							result = Config.HTTP_FAIL;
						}
						return result;
					}
				});
		new Thread(task).start();
		return task.get();
	}
	
	public static String getsessionId() {
		return sessionId;
	}

	/**
	 * @param url
	 *            发送请求的URL 无参数
	 * @return 服务器响应字符串
	 * @throws ExecutionException
	 * @throws InterruptedException
	 * @throws Exception
	 */
	public static String postRequest(final String url)
			throws InterruptedException, ExecutionException {
		final HttpClient httpClient = new DefaultHttpClient();
		FutureTask<String> task = new FutureTask<String>(
				new Callable<String>() {
					@Override
					public String call() throws ParseException, IOException {
						// 创建HttpPost对象。
						String murl = url;
						HttpPost post = new HttpPost(murl);
						// 如果传递参数个数比较多的话可以对传递的参数进行封装
						List<NameValuePair> params = new ArrayList<NameValuePair>();

						// 设置请求参数
						post.setEntity(new UrlEncodedFormEntity(params, "utf-8"));

						// 请求超时 add by risa
						httpClient.getParams().setParameter(
								CoreConnectionPNames.CONNECTION_TIMEOUT, 60000);// 60000
						// 读取超时 add by risa
						httpClient.getParams().setParameter(
								CoreConnectionPNames.SO_TIMEOUT, 60000);

						// 发送POST请求
						HttpResponse httpResponse = null;
						try {
							httpResponse = httpClient.execute(post);
						} catch (ConnectTimeoutException e) {
							Log.e("ConnectTimeoutException",
									"ConnectTimeoutException");
							e.printStackTrace();
						} catch (SocketTimeoutException e) {

							Log.e("SocketTimeoutException",
									"SocketTimeoutException");
							e.printStackTrace();

						}
						// 如果服务器成功地返回响应
						if (httpResponse.getStatusLine().getStatusCode() == 200) {
							// 获取服务器响应字符串
							String result = EntityUtils.toString(httpResponse
									.getEntity());
							return result;
						}
						return null;
					}
				});
		new Thread(task).start();
		return task.get();
	}

	public static String postRequestNomap(final String url)
			throws InterruptedException, ExecutionException {
		final HttpClient httpClient = new DefaultHttpClient();
		FutureTask<String> task = new FutureTask<String>(
				new Callable<String>() {
					@Override
					public String call() throws ParseException, IOException {
						// 创建HttpPost对象。
						HttpPost post = new HttpPost(url);
						// 如果传递参数个数比较多的话可以对传递的参数进行封装
						List<NameValuePair> params = new ArrayList<NameValuePair>();
						/*
						 * for(String key : rawParams.keySet()) { //封装请求参数
						 * params.add(new BasicNameValuePair(key ,
						 * rawParams.get(key))); }
						 */
						// 设置请求参数
						post.setEntity(new UrlEncodedFormEntity(params, "utf-8"));

						// 请求超时 add by risa
						httpClient.getParams().setParameter(
								CoreConnectionPNames.CONNECTION_TIMEOUT, 60000);// 60000
						// 读取超时 add by risa
						httpClient.getParams().setParameter(
								CoreConnectionPNames.SO_TIMEOUT, 60000);

						// 发送POST请求
						HttpResponse httpResponse = null;
						try {
							httpResponse = httpClient.execute(post);
						} catch (ConnectTimeoutException e) {
							Log.e("ConnectTimeoutException",
									"ConnectTimeoutException");
							e.printStackTrace();
						} catch (SocketTimeoutException e) {

							Log.e("SocketTimeoutException",
									"SocketTimeoutException");
							e.printStackTrace();

						}
						// 如果服务器成功地返回响应
						if (httpResponse.getStatusLine().getStatusCode() == 200) {
							// 获取服务器响应字符串
							String result = EntityUtils.toString(httpResponse
									.getEntity());

							return result;
						}
						return null;
					}
				});
		new Thread(task).start();
		return task.get();
	}

	
	public static String postRequestNomapSe(final String url,final String setsessionid)
			throws InterruptedException, ExecutionException {
		final HttpClient httpClient = new DefaultHttpClient();
		FutureTask<String> task = new FutureTask<String>(
				new Callable<String>() {
					@Override
					public String call() throws ParseException, IOException {
						// 创建HttpPost对象。
						String result;
						HttpPost post = new HttpPost(url);
						//post.setHeader("Cookie", "JSESSIONID=" + "03236F972DB06FD00F37BD0CEF92B433");
						if (null != setsessionid && !setsessionid.equals("")) {
							post.setHeader("Cookie", "JSESSIONID=" + setsessionid);
						}
						// 如果传递参数个数比较多的话可以对传递的参数进行封装
						List<NameValuePair> params = new ArrayList<NameValuePair>();
						/*
						 * for(String key : rawParams.keySet()) { //封装请求参数
						 * params.add(new BasicNameValuePair(key ,
						 * rawParams.get(key))); }
						 */
						// 设置请求参数
						post.setEntity(new UrlEncodedFormEntity(params, "utf-8"));

						// 请求超时 add by risa
						httpClient.getParams().setParameter(
								CoreConnectionPNames.CONNECTION_TIMEOUT, 60000);// 60000
						// 读取超时 add by risa
						httpClient.getParams().setParameter(
								CoreConnectionPNames.SO_TIMEOUT, 60000);

						// 发送POST请求
						HttpResponse httpResponse = null;
						try {
							httpResponse = httpClient.execute(post);
						} catch (ConnectTimeoutException e) {
							Log.e("postRequestNomapSe",
									"ConnectTimeoutException");
							e.printStackTrace();
						} catch (SocketTimeoutException e) {

							Log.e("postRequestNomapSe",
									"SocketTimeoutException");
							e.printStackTrace();

						}
						// 如果服务器成功地返回响应
						if (httpResponse.getStatusLine().getStatusCode() == 200) {
							// 获取服务器响应字符串
							result = EntityUtils.toString(httpResponse
									.getEntity());
							Log.e("postRequestNomapSe",
									result);
							//return result;
						}else{
							result = Config.HTTP_FAIL;
						}
						return result;
					}
				});
		new Thread(task).start();
		return task.get();
	}
	
	/**
	 * 
	 * @param url
	 *            发送请求的URL
	 * @return 服务器响应字符串
	 * @throws Exception
	 */
	public static String getRequestByNewClient(final String url)
			throws Exception {
		final String murl = Tool.getConfigUrl(Config.SERVER_URL, Config.LOGOUT_URL);
		FutureTask<String> task = new FutureTask<String>(
				new Callable<String>() {
					@Override
					public String call() throws Exception {
						HttpClient httpClient = new DefaultHttpClient();
						// 创建HttpGet对象。
						HttpGet get = new HttpGet(murl);
						// 请求超时 add by risa
						httpClient.getParams().setParameter(
								CoreConnectionPNames.CONNECTION_TIMEOUT, 60000);// 60000
						// 读取超时 add by risa
						httpClient.getParams().setParameter(
								CoreConnectionPNames.SO_TIMEOUT, 60000);
						// 发送GET请求
						HttpResponse httpResponse = httpClient.execute(get);
						// 如果服务器成功地返回响应
						if (httpResponse.getStatusLine().getStatusCode() == 200) {
							// 获取服务器响应字符串
							String result = EntityUtils.toString(httpResponse
									.getEntity());

							if (result.indexOf("[{") != -1) {
								result = result.replace("\n", "").replace("\r",
										"");
							}

							return result;

						} else {
							// Toast.makeText(HttpUtil.class, "未能正常获取数据 ！！",
							// Toast.LENGTH_LONG).show();
							System.out.println("<--can't return result-->");
						}
						return null;
					}
				});

		new Thread(task).start();
		return task.get();
	}

	public static String postRequestByFinalClient(final String url,
			final HttpClient httpClient, final Map<String, String> rawParams)
			throws InterruptedException, ExecutionException {
		FutureTask<String> task = new FutureTask<String>(
				new Callable<String>() {
					@Override
					public String call() throws ParseException, IOException {
						// 创建HttpPost对象。
						HttpPost post = new HttpPost(url);
						// 如果传递参数个数比较多的话可以对传递的参数进行封装
						List<NameValuePair> params = new ArrayList<NameValuePair>();
						for (String key : rawParams.keySet()) {
							// 封装请求参数
							params.add(new BasicNameValuePair(key, rawParams
									.get(key)));
						}
						// 设置请求参数
						post.setEntity(new UrlEncodedFormEntity(params, "utf-8"));

						// 请求超时 add by risa
						httpClient.getParams().setParameter(
								CoreConnectionPNames.CONNECTION_TIMEOUT, 60000);// 60000
						// 读取超时 add by risa
						httpClient.getParams().setParameter(
								CoreConnectionPNames.SO_TIMEOUT, 60000);

						// 发送POST请求
						HttpResponse httpResponse = null;
						try {
							httpResponse = httpClient.execute(post);
						} catch (ConnectTimeoutException e) {
							Log.e("ConnectTimeoutException",
									"ConnectTimeoutException");
							e.printStackTrace();
						} catch (SocketTimeoutException e) {

							Log.e("SocketTimeoutException",
									"SocketTimeoutException");
							e.printStackTrace();

						}
						// 如果服务器成功地返回响应
						if (httpResponse.getStatusLine().getStatusCode() == 200) {
							// 获取服务器响应字符串
							String result = EntityUtils.toString(httpResponse
									.getEntity());
							return result;
						}
						return null;
					}
				});
		new Thread(task).start();
		return task.get();
	}
}
